//
//  MainViewController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/12.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "MainViewController.h"

//客户服务
#import "BCCustomerServiceController.h"
//项目明细
#import "BCProjectDetailsController.h"
//分享
#import "BCShareRewardController.h"
//首页弹出广告
#import "BCHomeAdsController.h"

//url
#import "BCURLController.h"

//view
#import "HomeHeaderView.h"
//自定义顶部视图
#import "HomeNaviView.h"

//cell以及cellheader
#import "HomeOptimizationCell.h"
#import "HomeRecommendCell.h"
#import "CustomProjectHeaderView.h"

//refresh
#import "BCHomeRefreshHeader.h"
#import "BCRefreshAutoFooter.h"

//login
#import "GSCommonLoginViewController.h"
//切换区域
#import "MainChangeRegionController.h"

//
#import "BCProjectModel.h"

//request
#import "BCHomeDataRequest.h"

@interface MainViewController () <UITableViewDataSource,UITableViewDelegate,BCHomeRefreshHeaderDelegate,HomeHeaderViewDelegate>

@property (nonatomic, strong) UITableView *homeTable;

/**
 *BCHomeRefreshHeader
 */
@property (nonatomic, strong) BCHomeRefreshHeader *refreshHeader;
/**
 *refreshAutoFooter
 */
@property (nonatomic, strong) BCRefreshAutoFooter *refreshAutoFooter;

/**
 *HomeHeaderView
 */
@property (nonatomic, strong) HomeHeaderView *headerView;


/**
 *HomeNaviView
 */
@property (nonatomic, strong) HomeNaviView *naviView;

#pragma mark - sources
/**
 *optimizationSource 优选的数据源 section 0
 */
@property (nonatomic, strong) NSMutableArray *optimizationSource;
/**
 *recommendSource 推荐的数据源 > section 0
 */
@property (nonatomic, strong) NSMutableArray *recommendSource;

#pragma mark - requestData

/**
 *requestHomeData
 */
@property (nonatomic, strong) BCHomeData *requestHomeData;

@end

@implementation MainViewController

- (NSMutableArray *)optimizationSource {
    if (!_optimizationSource) {
        _optimizationSource = [NSMutableArray array];
    }
    return _optimizationSource;
}
- (NSMutableArray *)recommendSource {
    if (!_recommendSource) {
        _recommendSource = [NSMutableArray array];
    }
    return _recommendSource;
}

#pragma mark - getter views
- (HomeNaviView *)naviView {
    if (!_naviView) {
        _naviView = [HomeNaviView new];
        [self.view addSubview:_naviView];
        [_naviView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.view);
            make.left.right.mas_equalTo(self.view);
            make.height.mas_equalTo(0);
        }];
        //action
        [_naviView addServiceButtonTarget:self action:@selector(toCustomerServiceAction)];
        [_naviView addPrizeButtonTarget:self action:@selector(toPrizeAction)];
        [_naviView addRegionButtonTarget:self action:@selector(toChangeRegionAction)];
        //
        _naviView.iconImageView.userInteractionEnabled = true;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toShowHomeAdsAction)];
        [_naviView.iconImageView addGestureRecognizer:tap];
    }
    return _naviView;
}

- (HomeHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[HomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, [HomeHeaderView defaultHeight])];
        _headerView.delegate = self;
    }
    return _headerView;
}

- (BCHomeRefreshHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCHomeRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
        _refreshHeader.delegate = self;
    }
    return _refreshHeader;
}

- (BCRefreshAutoFooter *)refreshAutoFooter {
    if (!_refreshAutoFooter) {
        _refreshAutoFooter = [BCRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAutoFooterLoadMoreAction) needBottomSafeArea:false];
    }
    return _refreshAutoFooter;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupSubviews];
    //
    [self.homeTable addObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset)) options:NSKeyValueObservingOptionNew context:nil];
    //请求数据
    self.isLoadedData = false;
    [self requestHomeDataReg_id:nil init:true refresh:false];
}

- (void)setIsLoadedData:(BOOL)isLoadedData {
    [super setIsLoadedData:isLoadedData];
    //
    self.homeTable.scrollEnabled = isLoadedData;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view bringSubviewToFront:self.naviView];
    //
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //弹出广告
    [self autoShowHomeAdsAction];
}

//
- (void)setupSubviews {
    self.homeTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.homeTable.showsVerticalScrollIndicator = false;
    self.homeTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.homeTable.dataSource = self;
    self.homeTable.delegate = self;
    self.homeTable.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.homeTable];
    [self.homeTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    [self.homeTable registerClass:HomeRecommendCell.class forCellReuseIdentifier:NSStringFromClass(HomeRecommendCell.class)];
    [self.homeTable registerClass:HomeOptimizationCell.class forCellReuseIdentifier:NSStringFromClass(HomeOptimizationCell.class)];
    [self.homeTable registerClass:CustomProjectHeaderView.class forHeaderFooterViewReuseIdentifier:NSStringFromClass(CustomProjectHeaderView.class)];
    //
    [self.homeTable setTableHeaderView:self.headerView];
    //refreshHeader
    [self.homeTable setMj_header:self.refreshHeader];
    //
    [self.view layoutIfNeeded];
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(contentOffset))]) {
        CGPoint contentOffset = self.homeTable.contentOffset;
        [self.headerView layoutSubviewsWithTableViewContentOffset:contentOffset];
        [self.naviView layoutSubviewsWithTableViewContentOffset:contentOffset];
        //
        if (_refreshHeader) {
            if (!_refreshHeader.isRefreshing) {
                [self.naviView setPullingPercent:_refreshHeader.pullingPercent contentOffset:contentOffset];
            }
        }
    }
}
#pragma mark - BCHomeRefreshHeaderDelegate
- (void)home_beginRefreshing {
    [self.naviView beginRefreshing];
}
- (void)home_endRefreshing {
    [self.naviView endRefreshing];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isLoadedData) {
        if (section==0) {
            return self.optimizationSource.count;
        }else {
            return self.recommendSource.count;
        }
    }else {
        if (section==0) {
            return 1;
        }else {
            return 4;
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        BCProjectModel *model;
        if (self.isLoadedData) {
            model = self.optimizationSource[indexPath.row];
        }
        HomeOptimizationCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(HomeOptimizationCell.class)];
        cell.tableView = tableView;
        cell.cellData = model;
        return cell;
    }else {
        BCProjectModel *model;
        if (self.isLoadedData) {
            model = self.recommendSource[indexPath.row];
        }
        HomeRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(HomeRecommendCell.class)];
        cell.tableView = tableView;
        cell.cellData = model;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        return [HomeOptimizationCell defaultHeight];
    }else {
        return [HomeRecommendCell defaultHeight];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section!=0) {
        CustomProjectHeaderView *header = [[CustomProjectHeaderView alloc] initWithReuseIdentifier:NSStringFromClass(CustomProjectHeaderView.class)];
        header.isLoadedData = self.isLoadedData;
        header.title = self.requestHomeData.push.title;
        return header;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section==1) {
        if (self.isLoadedData) {
            return self.recommendSource.count==0?0.0:[CustomProjectHeaderView defaultHeight];
        }else {
            return [CustomProjectHeaderView defaultHeight];
        }
    }
    return 0.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [UIView new];
    footer.backgroundColor = [UIColor separatorViewColor];
    return footer;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    /**
     将headerView sendSubviewToBack 不然会挡住cell
     */
    [self.homeTable sendSubviewToBack:self.headerView];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isLoadedData) {
        BCProjectModel *model;
        if (indexPath.section==0) {
            model = self.optimizationSource[indexPath.row];
        }else {
            model = self.recommendSource[indexPath.row];
        }
        [self toProjectDetailsAction:model];
    }
}

#pragma mark - HomeHeaderViewDelegate
/**
 当头部信息点击后跳转
 */
- (void)homeHeaderViewMessageDidClicked:(BCHomeDataMessage *)mesage {
    if (mesage.url.length) {
        BCURLController *vc = [BCURLController new];
        vc.urlString = mesage.url;
        [self.navigationController pushViewController:vc animated:true];
    }
}

#pragma mark - 刷新
- (void)refreshHeaderAction {
    [self requestHomeDataReg_id:nil init:false refresh:true];
}
//loadMore
- (void)refreshAutoFooterLoadMoreAction {
    //do nothing
}

#pragma mark - 请求数据
/**
 请求首页数据 reg_id 详见参数
 */
- (void)requestHomeDataReg_id:(NSString *)reg_id init:(BOOL)init refresh:(BOOL)refresh {
    self.homeTable.mj_footer = nil;
    if (init) {
        [self.headerView bc_showLoading];
    }
    BCHomeDataRequest *request = [BCHomeDataRequest new];
    //
    request.reg_id = [BCUserManager sharedUser].reg_id;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init) {
            [wself.headerView bc_hiddenLoading];
        }
        if (refresh) {
            [wself.refreshHeader endRefreshing];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCHomeDataResponse *resp = result;
        [wself reloadHomeData:resp];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            if (init) {
                [wself.view bc_showError:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitErrorAction)];
            }
            
            NSString *errMsg = error.domain;
            [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
        }
    }];
    [request requestServer];
}
/**
 初始化请求时 返回错误
 */
- (void)requestInitErrorAction {
    [self.view bc_hiddenError];
    [self requestHomeDataReg_id:nil init:true refresh:false];
}


//请求数据成功后 重新加载数据
- (void)reloadHomeData:(BCHomeDataResponse *)resp {
    self.requestHomeData = resp.data;
}
- (void)setRequestHomeData:(BCHomeData *)requestHomeData {
    _requestHomeData = requestHomeData;
    if (requestHomeData) {
        self.isLoadedData = true;
        //
        self.naviView.flowData = requestHomeData.flow;
        self.headerView.homeData = requestHomeData;
        //
        [BCUserManager sharedUser].reg_id = requestHomeData.reg_id;
        
        //
        [self.optimizationSource removeAllObjects];
        [self.recommendSource removeAllObjects];
        //
        NSArray *selectedData = requestHomeData.selected.data;
        BCHomeSelectedTextModel *selectedText = requestHomeData.selected.text;
        if (selectedData.count) {
            for (int i=0; i<selectedData.count; i++) {
                BCProjectModel *project = selectedData[i];
                //
                project.repayCaption = selectedText.repay;
                project.countdownMess = selectedText.mess;
                [self.optimizationSource addObject:project];
            }
        }
        NSArray *pushData = requestHomeData.push.data;
        BCHomePushTextModel *pushText = requestHomeData.push.text;
        if (pushData.count) {
            for (int i=0; i<pushData.count; i++) {
                BCProjectModel *project = pushData[i];
                //
                project.repayCaption = pushText.repay;
                [self.recommendSource addObject:project];
            }
        }
        //
        [self.refreshAutoFooter setTitle:requestHomeData.flow.bottom forState:MJRefreshStateNoMoreData];
        [self.homeTable setMj_footer:self.refreshAutoFooter];
        [self.refreshAutoFooter endRefreshingWithNoMoreData];
        
        //
        [self.homeTable  reloadData];
    }else {
        
    }
    
    //
    [self autoShowHomeAdsAction];
}

#pragma mark - 跳转控制器
//客户服务
- (void)toCustomerServiceAction {
    BCCustomerServiceController *service = [BCCustomerServiceController new];
    service.serviceType = BCustomerServiceTypeService;
    [self.navigationController presentViewController:service animated:true completion:nil];
}
//领奖
- (void)toPrizeAction {
    if ([BCUserManager sharedUser].isLogin) {
        [BCShareRewardController showFromController:self.navigationController];
    }else {
        [GSCommonLoginViewController presentToCommloginController:self.navigationController];
    }
}
//切换区域
- (void)toChangeRegionAction {
    if (self.requestHomeData.region.count) {
        if (self.requestHomeData.region.count>0) {
            MainChangeRegionController *region = [MainChangeRegionController new];
            region.homeData = self.requestHomeData;
            [self.navigationController presentViewController:region animated:true completion:nil];
        }
    }
}


//项目明细
- (void)toProjectDetailsAction:(BCProjectModel *)model {
    BCProjectDetailsController *detail = [BCProjectDetailsController new];
    detail.projectId = [NSString stringWithFormat:@"%@",@(model.project_id)];
    [self.navigationController pushViewController:detail animated:true];
}


#pragma mark - 显示广告
- (void)autoShowHomeAdsAction {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (![BCAdsManager shared].isShowedHomeAds) {
            [self toShowHomeAdsAction];
        }
    });
}
- (void)toShowHomeAdsAction {
    if ([UIApplication sharedApplication].keyWindow!=[UIApplication sharedApplication].delegate.window) {
        return;
    }
    /**
     如果首页数据没有加载成功不显示 否则看起来比较尴尬
     */
    if (!self.requestHomeData) {
        return;
    }
    UIViewController *visibelController = [QMUIHelper visibleViewController];
    if (!visibelController || ![visibelController isEqual:self]) {
        return;
    }
    //
    [BCAdsManager shared].isShowedHomeAds = true;//
    NSArray *ads = [BCAdsManager shared].homeAds;
    if (ads.count) {
        CGRect showFrame = CGRectZero;
        if (self.requestHomeData) {
            showFrame = [self.naviView convertIconImageViewFrameToView:[UIApplication sharedApplication].keyWindow];
        }
        WEAK_SELF
        [BCHomeAdsController showFromController:self.navigationController forFrame:showFrame ads:ads selectedAdModelBlock:^(BCAdsDataModel * _Nonnull adModel) {
            [wself homeAdDidSelectModel:adModel];
        }];
    }
    //更新一下广告数据
    [[BCAdsManager shared] requestAdsData];
}
- (void)homeAdDidSelectModel:(BCAdsDataModel *)adModel {
    UIViewController *visibleController = [QMUIHelper visibleViewController];
    if (visibleController&&[visibleController isEqual:self]) {
        if (adModel.ad_url.length) {
            BCURLController *vc = [BCURLController new];
            vc.urlString = adModel.ad_url;
            [self.navigationController pushViewController:vc animated:true];
        }
    }
}


///
- (void)dealloc {
    [self.homeTable removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset))];
}

@end
